import { defineStore } from 'pinia'
import { UserState } from '@/store/interface'
import { ElMessage } from 'element-plus'
import { apiLogin, getLoginUserInfo } from '@/api/modules/login'
import { getToken, removeToken, setToken } from '@/utils/cookies'
import piniaPersistConfig from '@/config/piniaPersist'
import { LOGIN_CODE_EXTRA } from '@/config'
import { residueTokenSeconds } from '@/api/modules/user'

export const useUserStore = defineStore('user', {
  state: (): UserState => ({
    token: getToken() || '',
    userId: '',
    userName: '',
    loginName: '',
    role: {},
    deptment: {},
    userInfo: {},
    // token 有效期
    tokenSeconds: null,
    // 系统时间
    systemTimeStamp: null,
    
  }),
  getters: {},
  actions: {
    // 登录
    Login(userInfo: any) {
      return new Promise((resolve: any, reject: any) => {
        apiLogin(userInfo)
          .then((result: any) => {
            // 处理结果
            if (result.success) {
              setToken(result.data)
              this.token = result.data
            } else {
              ElMessage.error(result.message)
            }
            resolve(result)
          })
          .catch((error: any) => {
            if (LOGIN_CODE_EXTRA.findIndex((e) => e.code === error.code) != -1) {
              setToken(error.data)
              this.token = error.data
            }
            reject(error)
          })
      })
    },
    GetResidueTokenSeconds() {
      return new Promise((resolve, reject) => {
        residueTokenSeconds({ token: this.token })
          .then((res: any) => {
            if (res) {
              if(res.success){
                this.tokenSeconds = res.data.residueTokenSeconds
                this.systemTimeStamp = res.data.systemTimeStamp
                
              }
            }
            resolve(res)
            
          })
          .catch((error: any) => {
            console.log(error,'错误了')
            reject(error)
          })
      })
    },
    // 获取用户信息
    GetInfo() {
      return new Promise((resolve, reject) => {
        getLoginUserInfo({ token: this.token })
          .then((res: { success: any; data: unknown }) => {
            if (res?.success) {
              const user: any = res.data
              this.loginName = user.loginName
              this.userName = user.userName
              this.userId = user.userId
              this.role.code = user?.abType
              this.deptment.code = user?.deptment

              this.userInfo = user
            }
            resolve(res.data)
          })
          .catch((error: any) => {
            reject(error)
          })
      })
    },
    // 退出系统
    LogOut() {
      return new Promise((resolve, reject) => {
        resolve('1')
      })
    },

    // 前端退出
    FedLogOut() {
      removeToken()
      this.token = ''
      this.userInfo = {}
      this.role = {}
      this.deptment = {}
    },
    // Set GlobalState
    setUserState(key: keyof UserState, val: any) {
      this.$patch({ [key]: val })
    },
  },
  persist: piniaPersistConfig('user'),
})
